<template>
  <div class="bottom">
    <!-- 输入框 -->
    <van-cell-group>
      <van-field v-model="yzm" placeholder="请输入验证码" autofocus>
        <template #button>
          <van-button
            size="small"
            type="primary"
            @click="sendMsg"
            :disabled="btnFlag"
          >
            {{ text }}
          </van-button>
        </template>
      </van-field>
    </van-cell-group>
    <!-- 登录按钮 -->
    <van-button
      round
      type="info"
      size="large"
      @click="next"
      color="linear-gradient(to right, #ff6034, #ee0a24)"
      :disabled="flag"
    >
      下一步</van-button
    >
  </div>
</template>

<script>
import { dosendmsgcode, docheckcode } from "../../api/user";
import Vue from "vue";
import { Toast } from "vant";
Vue.use(Toast);
export default {
  data() {
    return {
      yzm: "",
      text: "发送验证码",
      time: 60,
      btnFlag: false,
    };
  },
  // 效果，时间变化
  methods: {
    sendMsg() {
      const timer = setInterval(() => {
        this.time--;
        if (this.time == 0) {
          clearInterval(timer);
          this.text = "重新发送验证码";
          this.btnFlag = false;
          this.time = 60;
        } else {
          this.text = this.time + "s后重新发送";
          this.btnFlag = true;
        }
      }, 1000);
      // 发送验证码
      setTimeout(() => {
        dosendmsgcode({ tel: localStorage.getItem("tel") }).then((res) => {
          console.log(res.data.data);
          this.yzm = res.data.data;
        });
      }, 1500);
    },
    // 验证验证码是否正确
    next() {
      docheckcode({ tel: localStorage.getItem("tel"), telcode: this.yzm }).then(
        (res) => {
          switch (res.data.code) {
            case "10007":
              Toast("验证码有误，请重新输入");
              break;
            case "200":
              this.$router.push("/register/three");
              break;
            default:
              break;
          }
        }
      );
    },
  },
  computed: {
    flag() {
      if (/^\d{5}$/.test(this.yzm)) {
        return false;
      } else {
        return true;
      }
    },
  },
};
</script>

<style scoped>
.bottom {
  width: 85%;
  margin: 10px auto;
}
</style>